package com.review.Test.ReentrantLock;

import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;

public class ReadWriteLock {
	
	ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    ReadLock rLock = lock.readLock();
    WriteLock wLock = lock.writeLock();
    
    private void read(){
    	try {
			rLock.lock();
			System.out.println(Thread.currentThread().getName() + "   read开始");
			Thread.sleep(3000);
			System.out.println(Thread.currentThread().getName() + "   read结束");
		} catch (Exception e) {
			// TODO: handle exception
		} finally{
			rLock.unlock();
		}
    }
    
    private void write(){
    	try {
    		wLock.lock();
			System.out.println(Thread.currentThread().getName() + "   write开始");
			Thread.sleep(3000);
			System.out.println(Thread.currentThread().getName() + "   write结束");
		} catch (Exception e) {
			// TODO: handle exception
		} finally{
			wLock.unlock();
		}
    }
    
    public static void main(String[] args) {
    	final ReadWriteLock readWriteLock = new ReadWriteLock();
		Thread t1 = new Thread(new Runnable() {
			@Override
			public void run() {
				readWriteLock.read();
			}
		}, "t1");
		
		
		Thread t2 = new Thread(new Runnable() {
			@Override
			public void run() {
				readWriteLock.read();
			}
		}, "t2");
		
		
		Thread t3 = new Thread(new Runnable() {
			@Override
			public void run() {
				readWriteLock.write();
			}
		}, "t3");
		
		Thread t4 = new Thread(new Runnable() {
			@Override
			public void run() {
				readWriteLock.write();
			}
		}, "t4");
		
		
//		t1.start();
//		t2.start();
		
		
//		t1.start();
//		t3.start();
		
		
		t3.start();
		t4.start();
	}
}
